package com.bustle.order;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.bustle.order.data.Lineitem;
import com.bustle.order.data.Order;
import com.bustle.order.data.Order.OrderStatus;
import com.bustle.order.data.Payment;
import com.bustle.order.data.dao.LineitemDao;
import com.bustle.order.data.dao.OrderDao;
import com.bustle.order.data.dao.PaymentDao;

@Local
public interface OrderManager
{

  public void createOrder(Order order);
  public void cancelOrder(Order orderToCancel);
  public Payment payOrder(int anOrderId);
  public double computePaymentPrice(int anOrderId);
  public String retrieveOrderStatus(Order order);
  public List<Order> getOrdersByUser(int idUser);
  public Order getById(int idOrder);

  @Stateless
  public class DefaultOrderManager implements OrderManager
  {

    @EJB
    private OrderDao orderDao;
    @EJB
    private PaymentDao paymentDao;
    @EJB
    private LineitemDao lineitemDao;
    @PersistenceContext(unitName = "bustle-soa-order-data")
    private EntityManager entityManager;

    @Override
    public void createOrder(Order order)
    {
      for (Lineitem lineitem : order.getLineItems())
      {
        lineitemDao.create(lineitem);
      }
      orderDao.create(order);
    }

    @Override
    public void cancelOrder(Order orderToCancel)
    {
      orderToCancel.setOrderStatus(OrderStatus.CANCELLED);
      orderDao.update(orderToCancel);
    }

    @Override
    public Payment payOrder(int anOrderId)
    {
      Order order = orderDao.retrieve(anOrderId);
      if (order.getOrderStatus() == OrderStatus.WAITING)
      {
        Payment payment = new Payment();
        payment.setOrder(order);
        payment.setDatePayment(new Date());
        payment.setTotalPrice(order.getTotalPrice());
        order.setOrderStatus(OrderStatus.PAID);
        orderDao.update(order);
        paymentDao.create(payment);
        return payment;
      }
      return null;
    }

    @Override
    public double computePaymentPrice(int anOrderId)
    {
      Order order = orderDao.retrieve(anOrderId);
      return order.getTotalPrice();
    }

    @Override
    public String retrieveOrderStatus(Order order)
    {
      return order.getOrderStatus().name();
    }

    @Override
    public List<Order> getOrdersByUser(int idUser)
    {
      String stringQuery = "SELECT o FROM Order o WHERE o.account.user.id = :paramId";
      Query query = entityManager.createQuery(stringQuery);
      query.setParameter("paramId", idUser);
      return query.getResultList();
    }

    @Override
    public Order getById(int idOrder)
    {
      Order order = orderDao.retrieve(idOrder);
      return order;
    }

  }

}
